<?php
namespace yitongpay\lib;

use think\facade\Config;

class SecurityUtils
{

    public static function encrypt($data)
    {
        $publickey = self::redPukey();
        openssl_public_encrypt($data, $result, $publickey);
        return base64_encode($result);
    }


    public static function bin2hex($str)
    {
        return strtoupper(bin2hex($str));
    }

    public static function hexToStr($str)
    {
        return pack('H*', $str);
    }

    public static function pubkeyEncrypt($source_data) {
        $pu_key = self::redPukey();
        $data = "";
        $dataArray = str_split($source_data, 117);
        foreach ($dataArray as $value) {
            $encryptedTemp = "";
            openssl_public_encrypt($value,$encryptedTemp,$pu_key);//公钥加密
            $data .= base64_encode($encryptedTemp);
        }
        return $data;
    }

    public static function redPukey()
    {
        //拼接加密公钥路径
        $key =  Config::get('yitong.rsa_public_key');
        $pem = chunk_split($key,64,"\n");//转换为pem格式的公钥
        $pem = "-----BEGIN PUBLIC KEY-----\n".$pem."-----END PUBLIC KEY-----\n";
        $publicKey = openssl_pkey_get_public($pem);
        return $publicKey;
    }
}